﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Globalization;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Runtime.InteropServices;

namespace NumberToTextField
{
    /// <summary>
    /// The field editor class
    /// </summary>  
    public class NumberToTextFieldEditor : UserControl, IFieldEditor
    {

        #region fields

        protected TextBox txtQuantity;
        protected TextBox txtLanguage;


        #endregion

        #region OnInit
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Page.MaintainScrollPositionOnPostBack = true; //required to keep section within view
            if (!this.IsViewStateEnabled) { this.EnableViewState = true; }
        }
        #endregion

        #region IFieldEditor Members

        public bool DisplayAsNewSection { get { return true; } }
        
        public void InitializeWithField(SPField field)
        {
            EnsureChildControls();
            NumberToTextField _f = null;
            try { _f = field as NumberToTextField; }
            catch { }

            if (_f != null)
            {
                if (!IsPostBack)
                {
                    txtQuantity.Text = (!string.IsNullOrEmpty(_f.QuantityColumn)) ? SPHttpUtility.HtmlDecode(_f.QuantityColumn) : string.Empty;
                    txtLanguage.Text = (!string.IsNullOrEmpty(_f.LocaleColumn)) ? SPHttpUtility.HtmlDecode(_f.LocaleColumn) : string.Empty;
                  
                }
            }

            // this bit must always happen, even when field is null
            if (!IsPostBack)
            {
            }
        }
        
        public void OnSaveChange(SPField field, bool isNewField)
        {
            NumberToTextField _f = null;
            try { _f = field as NumberToTextField; }
            catch { }

            if (_f != null)
            {                   
                _f.QuantityColumn = (!string.IsNullOrEmpty(txtQuantity.Text)) ? SPHttpUtility.HtmlEncode(txtQuantity.Text) : "";
                _f.LocaleColumn = (!string.IsNullOrEmpty(txtLanguage.Text)) ? SPHttpUtility.HtmlEncode(txtLanguage.Text) : "";
            }
        }

        #endregion
    }
}
